package com.gill.jwt.interceptor;

import com.gill.jwt.annotation.Login;
import com.gill.jwt.config.properties.JwtProperties;
import com.gill.jwt.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        // 方法未添加@Login注解，返回true
        Login annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        }else{
            return true;
        }
        if(annotation == null){
            return true;
        }
        // 获取header
        String token = request.getHeader(jwtProperties.getHeader());
        if(token == null){
            throw new SecurityException(jwtProperties.getHeader()+" can not be null");
        }
        // 校验token
        Boolean isValid = jwtUtil.isTokenValid(token);
        if(!isValid){
            throw new SecurityException(jwtProperties.getHeader()+" is illegal");
        }
        // 3. 如果校验成功，那么就将用户的信息设置到request的attribute里面
        Claims claims = jwtUtil.getClaimsFromToken(token);
        request.setAttribute("userId",claims.get("userId"));
        request.setAttribute("username",claims.get("username"));
        request.setAttribute("role",claims.get("role"));

        return true;
    }
}